<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="90px">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="调拨日期">
            <el-date-picker
              v-model="daterangeDbRq"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调拨到" prop="dbdGq">
            <el-input
              v-model="queryParams.dbdGq"
              placeholder="请输入调拨到的工区名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调拨状态" prop="dbZt">
            <el-select v-model="queryParams.dbZt" placeholder="请选择调拨状态" clearable>
              <el-option
                v-for="dict in dict.type.ejkdb_dbzt"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="调拨人" prop="dbR">
            <el-input
              v-model="queryParams.dbR"
              placeholder="请输入调拨人"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增调拨单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          :disabled="!selectedRow || (selectedRow.dbZt != '待调拨')"
        >修改调拨单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          :disabled="!selectedRow || (selectedRow.dbZt != '待调拨')"
        >删除调拨单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出Excel
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              class="fixedTableOne" height="300" v-loading="loading"
              :data="ejkdbList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="调拨状态" align="center" prop="dbZt" width="180">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ejkdb_dbzt" :value="scope.row.dbZt"/>
        </template>
      </el-table-column>
      <el-table-column label="调拨工区" align="center" prop="dbGq" />
      <el-table-column label="调拨日期" align="center" prop="dbRq" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dbRq, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调拨人" align="center" prop="dbR"/>
      <el-table-column label="调拨到" align="center" prop="dbdGq"/>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="调拨详情" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleDbXqClick(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="qdDb(scope.row)"
            v-if="scope.row.dbZt == '待调拨'"
          >确定调拨
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.dbZt == '待调拨'"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.dbZt == '待调拨'"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改二级库调拨对话框 -->
    <vxe-modal :title="title" v-model="open" width="70%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="100px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">调拨基本信息</span>
          </div>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="调拨日期" prop="dbRq">
                <el-date-picker clearable style="width: 100%;"
                                v-model="form.dbRq"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择调拨日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="调拨人" prop="dbR">
                <el-input v-model="form.dbR" placeholder="请输入调拨人"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="调拨工区" prop="dbGq">
                <el-input disabled v-model="form.dbGq" placeholder="请输入调拨工区"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="调拨到" prop="dbdGq">
                <el-select @change="dbGqJy" v-model="form.dbdGq" placeholder="请选择调拨到工区">
                  <el-option
                    v-for="dict in dict.type.sjhx_gq"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">调拨明细信息</span>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddEjkdbDbmx">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteEjkdbDbmx">删除</el-button>
            </el-col>
          </el-row>
          <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                    :data="ejkdbDbmxList" :row-class-name="rowEjkdbDbmxIndex" height="45vh"
                    @selection-change="handleEjkdbDbmxSelectionChange" ref="ejkdbDbmx">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column v-if="1 === 2" label="物资ID" align="center" prop="wzxxId"/>
            <el-table-column v-if="1 === 2" label="二级库物资ID" align="center" prop="ejkwzId"/>
            <el-table-column label="物资名称" align="center" prop="wzName"/>
            <el-table-column label="物资单位" align="center" prop="wzDw"/>
            <el-table-column label="物资分类" align="center" prop="wzFl"/>
            <el-table-column label="物资规格" align="center" prop="wzGg"/>
            <el-table-column label="物资专业" align="center" prop="wzZy"/>
            <el-table-column label="领取人" align="center" prop="lqr">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lqr" placeholder="请输入领取人"/>
              </template>
            </el-table-column>
            <el-table-column label="调拨数量" align="center" prop="dbSl">
              <template slot-scope="scope">
                <el-input type="number" @change="calculateKc(scope.$index)" v-model="scope.row.dbSl"
                          placeholder="请输入调拨数量"/>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="bz" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.bz" placeholder="请输入备注"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 检修组物资多选 -->
    <JxzWz ref="jxzWz"/>

    <!-- 二级库调拨详情 -->
    <EjkDbXq ref="ejkDbXq"/>
  </div>
</template>

<script>
import {addEjkdb, delEjkdb, getEjkdb, getEjkDbId, listEjkdb, updateEjkdb, updateQdDb} from "@/api/ejkgl/ejkdb";
import WccWz from "@/views/components/EjkWzDuoX/WccWz.vue";
import {getEjkwz} from "@/api/ejkgl/ejkwz";
import EjkDbXq from "@/views/ejkgl/ejkdb/components/EjkDbXq.vue";
import JxzWz from "@/views/components/EjkWzDuoX/JxzWz.vue";

export default {
  name: "Ejkdb",
  components: {JxzWz, EjkDbXq, WccWz},
  dicts: ['sjhx_gq', 'ejkdb_dbzt'],
  provide() {
    return {
      updateJxzWzLabel: (val) => {
        val.forEach(item => {
          // 检查是否已存在相同的 出厂编号
          const exists = this.ejkdbDbmxList.some(existingItem => existingItem.wzxxId === item.wzxxId);
          if (!exists) {
            this.ejkdbDbmxList.push(item);
          }
        })
      },
    };
  },
  data() {
    return {
      getEjkDbId: null, //从后端获取到的二级库调拨主键ID (UUID)
      selectedRow: null, // 保存当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedEjkdbDbmx: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 二级库调拨表格数据
      ejkdbList: [],
      // 调拨明细表格数据
      ejkdbDbmxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeDbRq: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dbRq: null,
        dbR: null,
        dbdGq: null,
        idWhere: null,
        userId: null,
        deptId: null,
        dbZt: null,
        deptName: null,
        dbGq: '检修组',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dbRq: [{required: true, message: "调拨日期不能为空", trigger: "blur"}],
        dbR: [{required: true, message: "调拨人不能为空", trigger: "blur"}],
        dbdGq: [{required: true, message: "调拨到工区不能为空", trigger: "blur"},],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //查询二级库调拨详情
    handleDbXqClick(row) {
      this.$refs.ejkDbXq.handleOpen(row)
    },
    //确定调拨
    qdDb(row) {
      let ejkdbId = row.ejkdbId
      this.$confirm('是否确认调拨? 调拨完成后将无法再次修改', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$modal.loading("正在完成调拨中，请稍后...");
        getEjkdb(ejkdbId).then(res => {
          let form = {
            ejkdbId: ejkdbId,
            dbGq: res.data.dbGq,
            dbRq: res.data.dbRq,
            dbR: res.data.dbR,
            dbdGq: res.data.dbdGq,
          };
          form.ejkdbDbmxList = res.data.ejkdbDbmxList
          updateQdDb(form).then(res => {
            this.getList()
            this.$modal.msgSuccess("调拨完成!");
            this.$modal.closeLoading();
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //不能调拨到本工区
    dbGqJy() {
      if (this.form.dbdGq == '检修组') {
        this.$modal.alertError("不能调拨到本工区!");
        this.form.dbdGq = ''
      }
    },
    //判断库存是否足够
    calculateKc(index) {
      const row = this.ejkdbDbmxList[index];
      let ejkwzId = row.ejkwzId
      getEjkwz(ejkwzId).then(res => {
        if (row.dbSl > res.data.kc) {
          this.$modal.alertError("出库数量大于库存, 该物资当前的库存为:" + res.data.kc);
          row.dbSl = null
        } else {

        }
      })
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询二级库调拨列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDbRq && '' != this.daterangeDbRq) {
        this.queryParams.params["beginDbRq"] = this.daterangeDbRq[0];
        this.queryParams.params["endDbRq"] = this.daterangeDbRq[1];
      }
      listEjkdb(this.queryParams).then(response => {
        this.ejkdbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ejkdbId: this.getEjkDbId,
        dbGq: '检修组',
        dbRq: null,
        dbR: this.$store.state.user.name,
        dbdGq: null,
        idWhere: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null,
        dbZt: null,
      };
      this.ejkdbDbmxList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDbRq = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ejkdbId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      getEjkDbId().then(res => {
        this.getEjkDbId = res.msg
        this.reset();
      })
      this.open = true;
      this.title = "添加二级库调拨";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ejkdbId = row.ejkdbId || this.ids
      getEjkdb(ejkdbId).then(response => {
        this.form = response.data;
        this.ejkdbDbmxList = response.data.ejkdbDbmxList;
        this.open = true;
        this.title = "修改二级库调拨";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.ejkdbDbmxList = this.ejkdbDbmxList;

          if (this.form.ejkdbDbmxList.length == 0) {
            this.$modal.msgError("调拨明细不能为空");
            return
          }
          for (let i = 0; i < this.form.ejkdbDbmxList.length; i++) {
            let item = this.form.ejkdbDbmxList[i]
            if (item.dbSl == undefined || item.dbSl == null || item.dbSl == '') {
              this.$modal.msgError("第" + (i + 1) + "行，调拨数量为空，请检查");
              return
            }
          }

          if (this.form.idWhere != null) {
            updateEjkdb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEjkdb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ejkdbIds = row.ejkdbId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delEjkdb(ejkdbIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 调拨明细序号 */
    rowEjkdbDbmxIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 调拨明细添加按钮操作 */
    handleAddEjkdbDbmx() {
      this.$refs.jxzWz.handleOpen(this.ejkdbDbmxList)
      // let obj = {};
      // obj.wzxxId = "";
      // obj.wzName = "";
      // obj.wzDw = "";
      // obj.wzFl = "";
      // obj.wzGg = "";
      // obj.wzZy = "";
      // obj.dbSl = "";
      // obj.bz = "";
      // this.ejkdbDbmxList.push(obj);
    },
    /** 调拨明细删除按钮操作 */
    handleDeleteEjkdbDbmx() {
      if (this.checkedEjkdbDbmx.length == 0) {
        this.$modal.msgError("请先选择要删除的调拨明细数据");
      } else {
        const ejkdbDbmxList = this.ejkdbDbmxList;
        const checkedEjkdbDbmx = this.checkedEjkdbDbmx;
        this.ejkdbDbmxList = ejkdbDbmxList.filter(function (item) {
          return checkedEjkdbDbmx.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleEjkdbDbmxSelectionChange(selection) {
      this.checkedEjkdbDbmx = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ejkgl/ejkdb/export', {
        ...this.queryParams
      }, `ejkdb_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
